package com.ssm.sport.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssm.sport.dto.ResponseVO;
import com.ssm.sport.entity.Category;
import com.ssm.sport.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin/category")
public class AdminCategoryController {

    @Autowired
    private CategoryService categoryService;
    
    @Value("${file.upload.path:${user.home}/sport-mall-uploads}")
    private String uploadBaseDir;
    
    /**
     * 保存分类
     */
    @PostMapping("/save")
    @ResponseBody
    public ResponseVO save(Category category, @RequestParam(required = false) MultipartFile imageFile, 
                          HttpServletRequest request) {
        try {
            // 处理图片上传
            if (imageFile != null && !imageFile.isEmpty()) {
                // 确保外部目录存在
                File externalDir = new File(uploadBaseDir);
                if (!externalDir.exists()) {
                    externalDir.mkdirs();
                }
                
                // 生成新的文件名
                String originalFilename = imageFile.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID().toString() + extension;
                
                // 保存到外部存储
                File targetFile = new File(externalDir, newFilename);
                imageFile.transferTo(targetFile);
                
                // 设置图片URL为相对路径
                category.setImage("/uploads/" + newFilename);
                
                // 为了当前实例能访问，也复制到static目录
                String staticPath = request.getServletContext().getRealPath("/static/uploads/");
                File staticDir = new File(staticPath);
                if (!staticDir.exists()) {
                    staticDir.mkdirs();
                }
                
                File staticFile = new File(staticDir, newFilename);
                Files.copy(targetFile.toPath(), staticFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
            
            // 设置默认值
            if (category.getStatus() == null) {
                category.setStatus(1); // 默认启用
            }
            
            // 设置默认排序
            if (category.getSort() == null) {
                category.setSort(0);
            }
            
            // 设置创建和更新时间
            Date now = new Date();
            if (category.getId() == null) {
                category.setCreateTime(now);
            }
            category.setUpdateTime(now);
            
            boolean success = categoryService.saveOrUpdate(category);
            return success ? ResponseVO.success("保存分类成功") : ResponseVO.error("保存分类失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseVO.error("图片上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有分类
     */
    @GetMapping("/list")
    @ResponseBody
    public ResponseVO list() {
        List<Category> categories = categoryService.list(new QueryWrapper<Category>().orderByAsc("sort"));
        return ResponseVO.success(categories);
    }
    
    /**
     * 删除分类
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public ResponseVO delete(@PathVariable Integer id) {
        boolean success = categoryService.removeById(id);
        return success ? ResponseVO.success("删除成功") : ResponseVO.error("删除失败");
    }
} 